using System.IO;
using BitTorrent.Client.Peer.Exceptions;

namespace BitTorrent.Client.Peer.Message.Standard {
    /// <summary>
    /// Peer message indicating when a piece has been successfully downloaded and
    /// verified via the hash.
    /// </summary>
    internal class Have : PeerMessage
    {
        public Have() {
            PieceIndex = -1; // Indicate not set
        }

        public Have(BinaryReader reader) {
            PieceIndex = ReadInt32(reader);
        }

        public int PieceIndex { get; set; }

        public override byte[] GetMessage() {
            var result = new byte[9];

            using (var memory = new MemoryStream(result)) {
                var writer = new BinaryWriter(memory);

                /// Length (fixed)
                writer.Write(ToBytes(5));
                writer.Write((byte)PeerMessageId.Have);

                if (PieceIndex < 0) {
                    throw new PeerMessageException("Unassigned PieceIndex.");
                }

                writer.Write(ToBytes(PieceIndex));

                writer.Flush();
            }

            return result;
        }
    }
}